from hurryoff.db.base import Base
from hurryoff.db import DBSession, Session
from hurryoff.db.Train import Train
from hurryoff import log

from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy import create_engine

class MyApp(object):
    __name__ = None
    __parent__ = None

    def __getitem__(self, key):
        session= DBSession()
        try:
            id = int(key)
        except (ValueError, TypeError):
            raise KeyError(key)

        query = session.query(Train).join(Train.stops).filter(Train.id==id)

        try:
            item = query.one()
            item.__parent__ = self
            item.__name__ = key
            return item
        except NoResultFound:
            raise KeyError(key)

    def get(self, key, default=None):
        try:
            item = self.__getitem__(key)
        except KeyError:
            item = default
        return item

    def __iter__(self):
        session= DBSession()
        query = session.query(Train)
        return iter(query)

root = MyApp()

def default_get_root(request):
    return root

def initialize_sql(db_string, db_echo):
    engine = create_engine(db_string, echo=db_echo)
    DBSession.configure(bind=engine)
    Session.configure(bind=engine)
    Base.metadata.bind = engine

def appmaker(db_string, db_echo):
    initialize_sql(db_string, db_echo)
    log.dbConnectionString = db_string
    return default_get_root
